package SearchTest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.SearchApplication;
import com.hmall.item.Item;
import com.hmall.mapper.TestItemMapper;
import com.hmall.pojo.JoinDataThread;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author HOLO
 * @create 2023-01-09 9:43
 * @discription
 */

@SpringBootTest(classes = SearchApplication.class)
public class InsertDocs {

    /**
     * 索引库名
     */
    public static final String INDEX_NAME = "hmall_test";

    /**
     * 注入RestHighLevelClient对象
     */
    @Autowired(required = false)
    private RestHighLevelClient restHighLevelClient;

    @Autowired(required = false)
    private TestItemMapper itemMapper;

    private final ExecutorService pool = Executors.newFixedThreadPool(32);

    //页显示数
    private final Integer size = 1000;

    /**
     * 作用: 用多线程导入ES
     * 用之前先去配置文件改一下 Es的IP地址
     */
    @Test
    public void passAllDataToES() {
        long be = System.currentTimeMillis();
        Page<Item> page = new Page<>(1, size);
        //定义查询条件 status = 1
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Item::getStatus, 1);
        //调用selectPage方法实现分页，分页的结果会被封装到Page对象中
        itemMapper.selectPage(page, wrapper);
        //总页数
        long pages = page.getPages();

        for (int i = 0; i < pages; i++) {
            //开启线程
            pool.submit(new JoinDataThread(itemMapper,
                            INDEX_NAME,     //索引库名
                            restHighLevelClient, //执行ES语句客户端
                            i + 1, //从第1页开始添加数据
                            size //页显示数
                    )
            );
        }
        //线程池停止接收其他任务(关闭线程池)
        pool.shutdown();
        while (true) {
            //判断线程池是否已经无线程运作, 无运作为true
            if (pool.isTerminated()) {
                System.out.println("线程池中的任务执行结束");
                break;
            }
        }
        long la = System.currentTimeMillis();
        System.out.println(la - be);
    }


    @Test
        //添加索引库和映射
    void insertIndexAndMapping() throws IOException {
        //创建索引仓库客户端对象
        IndicesClient indicesClient = restHighLevelClient.indices();
        //创建索引库
        CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
        //定义分词器
        String setting = "{\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"text_anlyzer\": {\n" +
                "          \"tokenizer\": \"ik_max_word\",\n" +
                "          \"filter\": \"py\"\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "          \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": false,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true,\n" +
                "          \"none_chinese_pinyin_tokenize\": false\n" +
                "        }\n" +
                "      }\n" +
                "    },\n" +
                "    \"index\":{\n" +
                "      \"max_result_window\":\"1000000\"\n" +
                "    }\n" +
                "  }";
        request.settings(setting, XContentType.JSON);
        //定义映射字符串
        String mapping = "{\n" +
                "    \"properties\": {\n" +
                "      \"id\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"name\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"copy_to\": \"all\"\n" +
                "      },\n" +
                "      \"price\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"stock\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"category\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"copy_to\": \"all\"\n" +
                "      },\n" +
                "      \"brand\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"copy_to\": \"all\"\n" +
                "      },\n" +
                "      \"spec\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"sold\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"commentCount\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"isAD\":{\n" +
                "        \"type\": \"boolean\"\n" +
                "      },\n" +
                "      \"all\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"text_anlyzer\",\n" +
                "        \"search_analyzer\": \"ik_max_word\"\n" +
                "      },\n" +
                "\t    \"suggestion\":{\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"text_anlyzer\",\n" +
                "\t\t    \"search_analyzer\": \"ik_max_word\"\n" +
                "      }\n" +
                "    }\n" +
                "  }";
        request.mapping(mapping, XContentType.JSON);
        CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

}
